package com.mjk.common.tools.gson.adapter.impl;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.mjk.common.util.TimeUtils;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimestampAdapterImpl extends TypeAdapter<Timestamp> {
	
	private static final String ZEORTIME = "0:00:00";
	
	@Override
	public void write(JsonWriter out, Timestamp value) throws IOException {
		if(ObjectUtils.isEmpty(value)){
			out.value("");
			return;
		}
		DateFormat format ;
		if(value.toString().endsWith(ZEORTIME)) {
			 format = new SimpleDateFormat("yyyy-MM-dd");
		}else {
			 format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		}
		String dateFormatAsString = format.format(new Date(value.getTime()));	
		out.value(dateFormatAsString);
	}

	@Override
	public Timestamp read(JsonReader in) throws IOException {
		if (in.peek() == JsonToken.NULL) {
			return null;
		}
		Date date = TimeUtils.parse(in.nextString());
		return new Timestamp(date.getTime());
	}

}
